package Day2025_02_18;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode15 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        ArrayList<List<Integer>> lists = new ArrayList<>();
        for (int k = nums.length - 1; k > 1; k--) {
            int left = 0, right = k - 1;
            while (left < right) {
                if (nums[left] + nums[right] + nums[k] == 0) {
                    lists.add(new ArrayList<>(Arrays.asList(nums[left], nums[right], nums[k])));
                    left++; right--;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                } else if (nums[left] + nums[right] + nums[k] > 0) {
                    right--;
                } else {
                    left++;
                }
            }
            while (k > 1 && nums[k] == nums[k - 1]) k--;
        }
        return lists;
    }
}
